package com.example.takeoff.config.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.takeoff.common.constants;
import com.example.takeoff.entity.user;
import com.example.takeoff.exception.ServiceException;
import com.example.takeoff.mapper.userMapper;
import com.example.takeoff.service.impl.userServiceImpl;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor
{
    @Autowired
    private userServiceImpl userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    {
        String token = request.getHeader("token");
        //如果不是映射方法，直接通过
        if (!(handler instanceof HandlerMethod))
            return true;
        //执行认证
        if (StrUtil.isBlank(token))
        {
            throw new ServiceException(constants.code_401, "无token,请重新登录");
        }
        // 获取 token 中的 user id
        String userId;
        try
        {
            userId = JWT.decode(token).getAudience().get(0);
        }
        catch (JWTDecodeException j)
        {
            throw new ServiceException(constants.code_401, "token验证失败，请重新登录");
        }

        LambdaQueryWrapper<user> qw = new LambdaQueryWrapper<>();
        qw.eq(user::getUserid, userId);
        user user = userService.getOne(qw);


        if (user == null)
        {
            throw new ServiceException(constants.code_401, "用户不存在，请重新登录");
        }

        // 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try
        {
            jwtVerifier.verify(token);
        }
        catch (JWTVerificationException e)
        {
            throw new ServiceException(constants.code_401, "token验证失败");
        }

        return true;
    }
}
